<?php

namespace App\Repositories;

use Exception;
use App\Models\User;
use App\Models\Image;
use App\Models\Inspection;
use App\Models\Inspection\Node;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use App\Exceptions\GeneralException;

/**
 * 巡检基础逻辑
 *
 * Date: 25/04/2018
 * @author George
 * @package App\Repositories
 */
class InspectionRepository
{
	/**
	 * 创建巡检记录
	 *
	 * Date: 27/04/2018
	 * @author George
	 * @param User $user
	 * @param array $attributes
	 * @param array $files
	 * @param Node $node
	 * @return $this|\Illuminate\Database\Eloquent\Model
	 * @throws GeneralException
	 */
	public function store(User $user, array $attributes, array $files,  Node $node)
	{
		try {
			DB::beginTransaction();
			$attributes['company_id'] = $user->company_id;
			$attributes['line_id'] = $node->circle->line->id;
			$attributes['circle_id'] = $node->circle->id;
			$attributes['node_id'] = $node->id;
			$attributes['node_name'] = $node->name;
			$attributes['user_id'] = $user->id;
			$attributes['user_name'] = $user->name;
			$attributes['location'] = $node->location;
			$inspection = Inspection::create($attributes);

			$images = [];
			foreach ($files as $image) {
				/**
				 * @var UploadedFile $image
				 */
				$path = $image->store('public/inspection');
				$images[] = Image::create([
					'path' => $path,
					'company_id' => $inspection->company_id,
					'project_id' => $inspection->project_id,
					'user_id' => $inspection->user_id,
					'imagetable_id' => $inspection->id,
					'imagetable_type' => 'inspection',
				]);
			}
			$inspection->images = $images;
			DB::commit();
			return $inspection;
		} catch (Exception $exception) {
			DB::rollBack();
			dd($exception->getMessage());
			throw new GeneralException('巡检失败');
		}
	}

	public function get()
	{

	}
}
